
import React from "react";
import { Table, type TableProps } from "@/components/base";
import type { AnyObject } from "antd/es/_util/type";
import { Resizable } from "react-resizable";
import { TableOperate } from './table-operate';
import { v4 as uuid } from 'uuid';
import styles from './index.module.less';
import "react-resizable/css/styles.css";

export interface IAdvancedTableProps<RecordType> extends TableProps<RecordType> {
    /** 宽度 */
    columnsWidth?: { [key: string]: number };
}

/** 高级表格 */
function AdvancedTableUi<RecordType = AnyObject>(props: IAdvancedTableProps<RecordType>) {

    const { columns = [], pagination, ...restProps } = props;
    const [columnsWidth, setColumnsWidth] = React.useState<{ [key: string]: number }>(props.columnsWidth || {});

    const handleResize = (index: number) => (_e: React.SyntheticEvent<Element>, { size }: any) => {
        if (columns[index]) {
            setColumnsWidth({
                ...columnsWidth,
                [`${columns[index].key}`]: size.width,
            });
        }
    };

    const mergedColumns = columns.map((col, index) => {
        return {
            ...col,
            key: col.key || uuid(), // 确保每列都有唯一的 key
            width: columnsWidth[`${col.key}`] || col.width,
            ellipsis: col.ellipsis || (col.width && true),
            onHeaderCell: (column: any) => ({
                width: columnsWidth[`${col.key}`] || column.width,
                onResize: handleResize(index),
            }),
        }
    }) as any;

    // 处理分页属性，确保 current 是正数
    const safePagination = React.useMemo(() => {
        if (pagination === false) return false;

        if (typeof pagination === 'object' && pagination !== null) {
            return {
                ...pagination,
                current: Math.max(pagination.current || 1, 1),
                pageSize: Math.max(pagination.pageSize || 10, 1),
                total: Math.max(pagination.total || 0, 0),
            };
        }

        return pagination;
    }, [pagination]);

    return (
        <Table
            {...restProps}
            columns={mergedColumns}
            pagination={safePagination}
            components={{
                ...props.components,
                header: {
                    cell: ResizableTitle,
                }
            }}
        />
    )
}

const ResizableTitle = (props: any) => {
    const { onResize, width, ...restProps } = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            handle={
                <span
                    className={styles.resizableHandle}
                    onClick={(e) => {
                        e.stopPropagation();
                    }}
                />
            }
            onResize={onResize}
            draggableOpts={{ enableUserSelectHack: false }}
        >
            <th {...restProps} />
        </Resizable>
    );
};

export const AdvancedTable = Object.assign(AdvancedTableUi, { Operate: TableOperate });